package com.powerunion.datacollection.dao.impl;

import java.io.BufferedReader;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import oracle.jdbc.OracleResultSet;
import oracle.sql.CLOB;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.FormGroupHeaderDao;
import com.powerunion.datacollection.model.jsonObject.GroupHeaderInfo;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;
import com.powerunion.util.query.jdbc.QueryParameters;

public class FormGroupHeaderDaoImpl extends JdbcBase implements FormGroupHeaderDao{
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			FormGroupHeaderDaoImpl.class);

	protected static final String sqlGetBYKey=  "select fset_id,header_cont from dc_form_groupHeader where fset_id=?";
	protected static final String sqlInsertSubTblFormCONT = "select header_cont from dc_form_groupHeader where fset_id=? for update";
	protected static final String sqlUpdateSubTblFormCONT = "update dc_form_groupHeader set row_fixed =? where fset_id=?";
	
	public boolean save(GroupHeaderInfo form) throws Exception {
		boolean isSuccess = false;

		String sql = "";
		String sql2 = "";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Writer writer = null;
		try {
			conn = this.getConnection();
			conn.setAutoCommit(false);
			GroupHeaderInfo iform = this.findFormByKey(form.getFormId());
			sql = sqlInsertSubTblFormCONT;
			if (iform == null) {//新增
				sql2 = "insert into dc_form_groupHeader(header_cont,fset_id) values(empty_clob(),?)";
			} else {//修改
				//清空原clob对象
				sql2 = "update dc_form_groupHeader set header_cont=empty_clob() where fset_id=?";

			}
			
			ps = conn.prepareStatement(sql2);
			ps.setString(1, form.getFormId());
			ps.executeUpdate();
			ps.close();
			
			ps = conn.prepareStatement(sql);
			ps.setString(1, form.getFormId());
			rs = ps.executeQuery();
			if(rs.next()) {
				oracle.sql.CLOB clob = (oracle.sql.CLOB)((oracle.jdbc.OracleResultSet)rs).getClob("header_cont");
				writer = clob.getCharacterOutputStream();
				writer.write(form.getHeaderCont());
				writer.flush();
			}
			conn.commit();
			isSuccess = true;
		
		} catch (Exception e) {
			if(conn != null){
				try{
					conn.rollback();
				}catch(SQLException e1){
					e1.printStackTrace();
				}
			}
			logger.error("",e);
			throw new Exception("save:保存嵌套列头定义信息" + Constants.FAIL);
		}finally{
			if(writer != null){
				writer.close();
				writer = null;
			}
			DBUtils.close(rs,ps, conn);
		}
	
		return isSuccess;
	}

	public GroupHeaderInfo findFormByKey(String id) throws DaoException {
		String sql =  sqlGetBYKey;
		QueryParameters params = new QueryParameters();
		params.addParameter(id, Types.VARCHAR);
		GroupHeaderInfo form = null;
		try {
			form = (GroupHeaderInfo) this.findByKey(sql, params, "getGroupHeaderInfo");
		} catch (Exception e) {
			logger.error("findFormByKey:" + Constants.SEARCH + "form"
					+ Constants.FAIL,e);
			throw new DaoException("search db record error!");
		}

		return form;
	}

	public final GroupHeaderInfo getGroupHeaderInfo(ResultSet rs) throws Exception {
		GroupHeaderInfo form = new GroupHeaderInfo();

		form.setFormId(rs.getString("fset_id"));
		CLOB headerInfo  = ((OracleResultSet)rs).getCLOB("header_cont");
		form.setHeaderCont(this.ClobToString(headerInfo));

		return form;
	}
	
	// 将字CLOB转成STRING类型 
	private String ClobToString(CLOB clob) throws Exception {

		if(clob == null)return "";
		String reString = "";
		Reader is = clob.getCharacterStream();// 得到流
		BufferedReader br = new BufferedReader(is);
		StringBuffer sb = new StringBuffer();
		try{
			String s = br.readLine();
			
			while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
				sb.append(s);
				s = br.readLine();
			}
			
		}catch (Exception e) {
			logger.error("读取内容出错: " + e);
			throw new Exception("读取内容出错! " + e);
		} finally {
			if (is != null){
				is.close();
				is = null;
			}
			if (br != null){
				br.close();
				br = null;
			}
		}

		reString = sb.toString();
		return reString;
	} 
	
	public boolean update4RowFixed(String formId,int rowFixed)throws DaoException {
		UpdateOperator update = new UpdateOperator();
		update.setSql(sqlUpdateSubTblFormCONT);

		update.addParameter(new SqlParameter(SqlType.INTEGER, new Integer(rowFixed)));
		update.addParameter(new SqlParameter(SqlType.VARCHAR, formId));
	
		
		try {
			update.access();
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("update4RowFixed throw error!");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	


}
